//
//  NSString+STString.m
//  ShaBaoOnline
//
//  Created by huang yong on 16/7/11.
//  Copyright © 2016年 com.ShaBaoOnline.www. All rights reserved.
//

#import "NSString+STString.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation NSString (STString)
//得到前一天
+ (NSString *)cutOutLastFourStr:(NSString *)cardStr WithNum:(NSInteger)num {
    NSString *returnStr= nil;
    returnStr =  [cardStr substringFromIndex:cardStr.length- num ];
    
    return returnStr;
}

+ (NSString *)getYesterdaywithStr:(NSString *)bill_timeStr {
    NSString *str = nil;
    NSString *timeStr = [self getToday];
    NSString *subStr = [timeStr substringToIndex:[timeStr length] - 2];
    NSString *baseStr = @"220000";
    if (bill_timeStr.length == 1) {
        bill_timeStr = [NSString stringWithFormat:@"0%@",bill_timeStr];
    }
    NSString *newStr = [NSString stringWithFormat:@"%@%@%@",subStr,bill_timeStr,baseStr];
    NSDateFormatter*df = [[NSDateFormatter alloc]init];//格式化
    [df setDateFormat:@"yyyyMMddHHmmss"];
    [df setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"] ];
    NSDate*date =[[NSDate alloc]init];
    date =[df dateFromString:newStr];
    str = [NSString stringWithFormat:@"%@",date];
    
    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:date];//前一天
    NSDate *nextDay = [NSDate dateWithTimeInterval:24*60*60 sinceDate:date];//后一天
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"zh_CN"];
    [format setTimeZone:timeZone];
    [format setDateFormat:@"yyyyMMddHHmmss"];
    
    NSString* ruturnStr = [format stringFromDate:lastDay];
    NSLog(@"re= %@",ruturnStr);
    NSRange range = NSMakeRange(6,2);
    NSString *endStr = [ruturnStr substringWithRange:range];
    return endStr;
}

+ (NSString *)getToday {
    NSDate* today = [NSDate date];
    NSDateFormatter*df = [[NSDateFormatter alloc]init];//格式化
    [df setDateFormat:@"yyyyMMdd"];
    NSString* s1 = [df stringFromDate:today];
    NSLog(@" s1s1s1s%@",s1);
    NSDate* date = [df dateFromString:s1];
    //转换时间格式
    NSDateFormatter*df2 = [[NSDateFormatter alloc]init];//格式化
    [df2 setDateFormat:@"yyyyMMdd"];
    [df2 setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    NSLog(@"%@",[df2 stringFromDate:date]);
    NSString *todayStr = [df2 stringFromDate:date];
    return todayStr;
    
}
// 判断是否是整型

+ (BOOL)isPureInt:(NSString *)string
{
    　　NSScanner* scan = [NSScanner scannerWithString:string];
    　　int val;
    　　return [scan scanInt:&val] && [scan isAtEnd];
}
//判断是否为空
- (BOOL)stringIsEmpty{
    if([self isKindOfClass:[NSNull class]]){
        return YES;
    }
    NSString *text = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([text length] == 0) {
        return YES;
    }
    return NO;
}
//MD5加密
- (id)MD5{
    const char *cStr = [self UTF8String];
    unsigned char digest[16];
    unsigned int x=(int)strlen(cStr) ;
    CC_MD5( cStr, x, digest );
    // This is the md5 call
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}

//手机号码合法性判断
-(BOOL)validateMobile{
    NSString *MobileRegex = @"^0?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[0-9])[0-9]{8}$";
    NSPredicate *phoneNum = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",MobileRegex];
    return [phoneNum evaluateWithObject:self];
}
//身份证合法性判断最终版;
+ (BOOL)validateTruePeopleIDCode:(NSString *)identityCard {

    BOOL flag;
    if (identityCard.length <= 0)
    {
        flag = NO;
        return flag;
    }
    
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    flag = [identityCardPredicate evaluateWithObject:identityCard];
    
    
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if(flag)
    {
        if(identityCard.length==18)
        {
            //将前17位加权因子保存在数组里
            NSArray * idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
            
            //这是除以11后，可能产生的11位余数、验证码，也保存成数组
            NSArray * idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
            
            //用来保存前17位各自乖以加权因子后的总和
            
            NSInteger idCardWiSum = 0;
            for(int i = 0;i < 17;i++)
            {
                NSInteger subStrIndex = [[identityCard substringWithRange:NSMakeRange(i, 1)] integerValue];
                NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
                
                idCardWiSum+= subStrIndex * idCardWiIndex;
                
            }
            
            //计算出校验码所在数组的位置
            NSInteger idCardMod=idCardWiSum%11;
            
            //得到最后一位身份证号码
            NSString * idCardLast= [identityCard substringWithRange:NSMakeRange(17, 1)];
            
            //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
            if(idCardMod==2)
            {
                if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"])
                {
                    return flag;
                }else
                {
                    flag =  NO;
                    return flag;
                }
            }else
            {
                //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                if([idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]])
                {
                    return flag;
                }
                else
                {
                    flag =  NO;
                    return flag;
                }
            }
        }
        else
        {
            flag =  NO;
            return flag;
        }
    }
    else
    {
        return flag;
    }



}


//身份证合法性判断
-(BOOL)validateIdentityCard{
    NSString *indetityCardRegex = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCard = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",indetityCardRegex];
    return [identityCard evaluateWithObject:self];
}
//密码合法性判断
-(BOOL)validatePassword{
    NSString *passwordRegex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
    NSPredicate *password = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passwordRegex];
    return [password evaluateWithObject:self];
    
}
//含有六位数字
-(BOOL)validatePhoneCode{
    NSString *codeRegex = @"^[0-9]{6}$";
    NSPredicate *phondCode = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",codeRegex];
    return [phondCode evaluateWithObject:self];
}

//邮箱地址的正则表达式
- (BOOL)isValidateEmail{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}
- (BOOL)isValidateNumAndA{
    
    NSString *numCheck = @"[A-Z0-9a-z]";
    
    NSPredicate *numTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",numCheck];
    
    return [numTest evaluateWithObject:self];
    
}

//认证使用
- (NSString *)Base64EncodedStringFromString:(NSString *)string {
    NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
    NSUInteger length = [data length];
    NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    
    uint8_t *input = (uint8_t *)[data bytes];
    uint8_t *output = (uint8_t *)[mutableData mutableBytes];
    
    for (NSUInteger i = 0; i < length; i += 3) {
        NSUInteger value = 0;
        for (NSUInteger j = i; j < (i + 3); j++) {
            value <<= 8;
            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }
        
        static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        
        NSUInteger idx = (i / 3) * 4;
        output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
        output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
        output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6)  & 0x3F] : '=';
        output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0)  & 0x3F] : '=';
    }
    
    return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}

//是否有中文
- (BOOL)validateChinese{
    NSString *chineseRegex = @"^[\u4e00-\u9fa5]*$";
    NSPredicate *chinese = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",chineseRegex];
    return [chinese evaluateWithObject:self];
}
//判断数字
/**
 *  『正则表达式；推荐使用，不用循环遍历，控制更灵活』判断字符串内容是否是有效数字
 *
 *  @param string 需要验证的字符串
 *
 *  @return 字符串内容是否是有效数字
 */
- (BOOL)validateNumberByRegExp {
    BOOL isValid = YES;
    NSUInteger len = self.length;
    if (len > 0) {
        NSString *numberRegex = @"^[0-9]*$";
        NSPredicate *numberPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegex];
        isValid = [numberPredicate evaluateWithObject:self];
    }
    return isValid;
}
@end
